
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:path_provider/path_provider.dart';
import 'package:rtk_ota_plugin/rtk_ota_plugin.dart';
import 'package:rtk_ota_plugin/rtk_status.dart';
import 'package:rtk_ota_plugin_example/util/app_all_value.dart';
import 'package:rtk_ota_plugin_example/util/http_api.dart';

//固件升级页面
class OtaPage extends StatefulWidget {
  String? mac;
  String? name;
  OtaPage({this.mac,this.name});

  @override
  State<OtaPage> createState() => _OtaPageState();
}

class _OtaPageState extends State<OtaPage> {

  // String fileNetWorkPath = "https://mp-1d374e45-404a-4b05-b029-40992bd928d2.cdn.bspapp.com/J2208A_V033_1_20230928.zip";
  String fileNetWorkPath = "https://mp-1d374e45-404a-4b05-b029-40992bd928d2.cdn.bspapp.com/J2203_03_V000_8_20230613.zip";
  String filePath = "未下载";
  late String savePath;
  double _downloadRatio = 0.0;
  String _downloadIndicator = '0.00%';
  late CancelToken _token;
  bool _downloading = false;
  TextEditingController filePathController = TextEditingController();
  String framePath = "未选择";
  String uiPath = "未选择";
  String updateFirmwareTip = "";
  AppAllValueController controller = Get.find();
  //是否处于更新设备中
  bool isUpdate = false;
  //更新文件是否下载完成
  bool isDownFile = false;

  @override
  void initState() {
    getSavePath();
    super.initState();
    filePathController.text = fileNetWorkPath;
    controller.connectDevice();
    RtkOtaPlugin().otaListener((type, progress){
      switch(type){
        case RtkStatus.STATUS_DEVICE_CONNECTING:
          setState(() {
            updateFirmwareTip = "设备连接中";
          });
          break;
        case RtkStatus.STATUS_READY_FINISH:
          setState(() {
            updateFirmwareTip = "准备完成";
          });
          break;
        case RtkStatus.STATUS_OTA_FINISH:
          setState(() {
            updateFirmwareTip = "OTA环境准备结束";
          });
          break;
        case RtkStatus.STATUS_OTA_READYING:
          setState(() {
            updateFirmwareTip = "正在准备OTA环境";
          });
          break;
        case RtkStatus.STATUS_UPGRADING:
          setState(() {
            updateFirmwareTip = "进度:${progress}%";
          });
          break;
        case RtkStatus.STATUS_UPGRAD_SUCC:
          setState(() {
            updateFirmwareTip = "更新完成";
          });
          isUpdate = false;
          break;
      }
    });
  }


  ///获取保存的路径
  void getSavePath(){
    getTemporaryDirectory()
        .then((tempDir) => {savePath = tempDir.path + 'update.zip'});
  }

  ///下载文件
  void _downloadFile() {
    if (_downloading == true) {
      return;
    }
    _token = CancelToken();
    _downloading = true;
    HttpApi().doDownload(filePathController.text, savePath, cancelToken: _token,
        progress: (int received, int total) {
          // 下载进度
          setState(() {
            _downloadRatio = (received / total);
            if (_downloadRatio == 1) {
              _downloading = false;
            }
            _downloadIndicator = (_downloadRatio * 100).toStringAsFixed(2) + '%';
            filePath = "下载进度: $_downloadIndicator";
            print("下载进度: $_downloadIndicator");
          });
        }, completion: () {
          // 下载成功
          _downloading = false;
          isDownFile = true;
          print("下载完成:");
          setState(() {
            filePath = savePath;
          });
          RtkOtaPlugin().setFilePath(savePath);
          // FlutterLoadingHud.showToast(message: "\"下载完成\"");
        }, failure: (error) {
          // 下载出错
          _downloading = false;
          setState(() {
            filePath = "下载出错";
          });
          print("下载出错:${error.toString()}");
          // FlutterLoadingHud.showToast(message: error.message);
        });
  }
  ///取消下载
  void _cancelDownload() {
    if (_downloadRatio < 1.0) {
      _token.cancel();
      _downloading = false;
      setState(() {
        _downloadRatio = 0;
        _downloadIndicator = '0.00%';
      });
    }
  }
  ///删除文件
  void _deleteFile() {
    try {
      File downloadedFile = File(savePath);
      if (downloadedFile.existsSync()) {
        downloadedFile.delete();
      } else {
        print("文件不存在");
      }
    } catch (e) {
      print("删除文件异常");
    }
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("固件升级".tr),
      ),
      body: Column(
        mainAxisSize: MainAxisSize.max,
        children: [
          buildFilePathWidget(),
          buildDownFile(),
          buildUpdateFirmwareFile(),
        ],
      ),
    );
  }

  Widget buildFilePathWidget(){
    return Container(
      margin: EdgeInsets.only(left: 10,right: 10),
      height: 100,
      child: Row(
        children: [
          Text('升级文件地址：'.tr),
          Expanded(child: TextField(
            controller: filePathController,
            decoration: InputDecoration(
                hintText: '请输入升级文件路径'.tr
            ),
            textAlign: TextAlign.center,
            maxLines: null,
            keyboardType: TextInputType.text,
            textInputAction: TextInputAction.done,
          ))
        ],
      ),
    );
  }

  Widget buildDownFile(){
    return Container(
      margin: const EdgeInsets.only(left: 10,right: 10),
      height: 80,
      child: Row(
        mainAxisSize: MainAxisSize.max,
        children: [
          Container(
            width: 100,
            margin: const EdgeInsets.only(right: 10),
            child: ElevatedButton(
              child: Text('下载文件'.tr),
              onPressed: () async {
                if(filePathController.text.isNotEmpty){
                  _downloadFile();
                }
              },
            ),
          ),
          Expanded(child: Text(filePath))
        ],
      ),
    );
  }


  Widget buildUpdateFirmwareFile(){
    return Container(
      margin: const EdgeInsets.only(left: 10,right: 10),
      height: 40,
      child: Row(
        mainAxisSize: MainAxisSize.max,
        children: [
          Container(
            width: 200,
            margin: const EdgeInsets.only(right: 10),
            child: ElevatedButton(
              child: Text('固件升级'.tr),
              onPressed: () async {
                if(isDownFile){
                  if(isUpdate){
                    controller.showContentDialog("正在更新中，请勿重复点击".tr);
                  }else{
                    update(savePath);
                  }
                }else{
                  controller.showContentDialog("更新文件未下载".tr);
                }
              },
            ),
          ),
          Expanded(child: Text(updateFirmwareTip))
        ],
      ),
    );
  }

  ///开始升级
  void update(String path){
    isUpdate = true;
    controller.disConnectDevice();
    if(Platform.isAndroid){
      Future.delayed(Duration(seconds: 1),(){
        RtkOtaPlugin().initDfuAdapter(widget.mac!,path);
      });
    }else{
      Future.delayed(Duration(seconds: 1),(){
        RtkOtaPlugin().initIosDfuAdapter(widget.name!,path);
      });

    }
  }

}
